package com.lbw.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lbw.config.Comment;
import com.lbw.entity.QuestionEntity;
import com.lbw.entity.WrongEntity;
import com.lbw.result.Result;
import com.lbw.result.ResultFactory;
import com.lbw.service.QuestionEntityService;
import com.lbw.service.WrongEntityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lbw
 * @since 2020-09-13
 */
@RestController
@RequestMapping("/questionEntity")
@Api(tags = "题库")
public class QuestionEntityController {

    @Autowired
    private QuestionEntityService questionEntityService;

    @Autowired
    private WrongEntityService wrongEntityService;

    /**
     * 添加题目，申论或行测
     * @param questionEntityList
     * @return
     * @throws IOException
     */
    @PostMapping("/insertQuestion")
    @ApiOperation("添加题目")
    public Result insertQuestion(@ApiParam("题目集合对象，申论时传集合") @RequestBody List<QuestionEntity> questionEntityList) throws IOException {

        boolean save = questionEntityService.insertQuestion(questionEntityList);
        if (save) {
            return ResultFactory.success(true);
        }
        return ResultFactory.fail("添加题目失败！");
    }

    /**
     * 在视频播放过程中查询出题目，通过科目与章节查询
     *
     * @param type
     * @param chapterId
     * @return
     */
    @PostMapping("/selectQuestionByVideo")
    @ApiOperation("在视频播放过程中查询出题目，（只查询行测题目）")
    public Result selectQuestionByVideo(@ApiParam("科目类型（1为行测，2为申论）") @RequestParam("type") Integer type,
                                        @ApiParam("题目集合对象，申论时传集合") @RequestParam("chapterId") String chapterId) {
        LambdaQueryWrapper<QuestionEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(QuestionEntity::getType, type)
                .eq(QuestionEntity::getChapter, chapterId);
        //查询出多个题目
        List<QuestionEntity> questionEntityList = questionEntityService.list(lambdaQueryWrapper);
        if (questionEntityList != null && !questionEntityList.isEmpty()) {
            Random random = new Random();
            QuestionEntity questionEntity = questionEntityList.get(random.nextInt(questionEntityList.size()));
            return ResultFactory.success(questionEntity);
        }
        return ResultFactory.success(null);
    }

    /**
     * 判断是否为错题，如果为错题则向错题库插入，正确则返回题目信息
     *
     * @param questionId 题目id
     * @param stuId      学生id
     * @param answer     答案
     * @return
     */
    @PostMapping("/judgmentQuestion")
    @ApiOperation("判断是否为错题，视频抽取题目过程")
    public Result judgmentQuestion(@RequestParam("questionId") String questionId,
                                   @RequestParam("stuId") String stuId,
                                   @RequestParam("answer") String answer) {
        QuestionEntity questionEntity = questionEntityService.getById(questionId);
        if (answer.equals(questionEntity.getRightAnswer())) {
            //答案正确
            return ResultFactory.success(questionEntity);
        } else {
            //答案错误,插入到错题库
            LambdaQueryWrapper<WrongEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WrongEntity::getStuId, stuId)
                    .eq(WrongEntity::getQuestionId, questionId);
            WrongEntity wrongEntity = wrongEntityService.getOne(lambdaQueryWrapper);
            if (wrongEntity == null) {
                wrongEntity = new WrongEntity();
                wrongEntity.setQuestionId(questionId);
                wrongEntity.setStuId(stuId);
            }
            wrongEntity.setLastWrongAnswer(answer);
            wrongEntityService.saveOrUpdate(wrongEntity);
            return ResultFactory.failData("回答错误！", questionEntity);
        }

    }

    /**
     * 通过课程以及章节Id查询出题目,分页
     *
     * @param chapterId 章节Id
     * @param type 科目类型
     * @return
     */
    @PostMapping("/selectQuestionByChapterAndSubjectPage")
    @ApiOperation("通过课程以及章节Id查询出题目,分页")
    public Result selectQuestionByChapterAndSubjectPage(@ApiParam("章节号") @RequestParam("chapterId") String chapterId,
                                                        @ApiParam("科目类型（1为行测，2为申论）") @RequestParam("type") Integer type,
                                                    @ApiParam("当前页") @RequestParam(value = "pageNo") Integer pageNo,
                                                    @ApiParam("页大小") @RequestParam(value = "pageSize") Integer pageSize) {

        IPage<QuestionEntity> questionList = questionEntityService.selectQuestionByChapterAndSubjectPage(chapterId, type,pageNo,pageSize);
        return ResultFactory.success(questionList);
    }

    /**
     * 通过课程以及章节Id查询出题目,不分页
     *
     * @param chapterId 章节Id
     * @param type 科目类型
     * @return
     */
    @PostMapping("/selectQuestionByChapterAndSubject")
    @ApiOperation("通过课程以及章节Id查询出题目,不分页")
    public Result selectQuestionByChapterAndSubject(@ApiParam("章节号") @RequestParam("chapterId") String chapterId,
                                                    @ApiParam("科目类型（1为行测，2为申论）") @RequestParam("type") Integer type) {

        List<QuestionEntity> questionList = questionEntityService.selectQuestionByChapterAndSubject(chapterId, type);
        return ResultFactory.success(questionList);
    }

    /**
     * 通过题目关键字查询出题目
     * @param keyWord   搜索关键字
     * @return
     */
    @PostMapping("/selectQuestionByKeyWord")
    @ApiOperation("通过题目关键字查询出题目")
    public Result selectQuestionByKeyWord(@ApiParam("关键词") @RequestParam(value = "keyWord") String keyWord,
                                          @ApiParam("当前页") @RequestParam(value = "pageNo") Integer pageNo,
                                          @ApiParam("页大小") @RequestParam(value = "pageSize") Integer pageSize) {

        IPage<QuestionEntity> questionEntityIPage = questionEntityService.selectQuestionByKeyWord(keyWord, pageNo, pageSize);
        return ResultFactory.success(questionEntityIPage);
    }

}

